package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.*;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.heima.media.service.IWmUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author wsj
 * @since 2022-03-11
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Override
    public ResponseResult listByPage(WmNewsPageDto dto) {
        //获取线程中的user
        User user = MediaThreadLocalUtil.get();
        if (user==null) {
            //如果用户不存在，返回提示：需要登录
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建分页条件
        IPage<WmNews> page=new Page<>(dto.getPage(),dto.getSize());
        //构建查询条件
        LambdaQueryWrapper<WmNews> query=new LambdaQueryWrapper<>();
        query.eq(WmNews::getUserId,user.getId());
        if (dto.getChannelId()!=null) {
            query.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if (dto.getBeginPubDate()!=null) {
            query.ge(WmNews::getCreatedTime,dto.getBeginPubDate());
        }
        if (dto.getEndPubDate()!=null) {
            query.le(WmNews::getCreatedTime,dto.getEndPubDate());
        }
        if (!StringUtils.isEmpty(dto.getKeyword())) {
            query.like(WmNews::getTitle,dto.getKeyword());
        }
        if (dto.getStatus()!=null) {
            query.eq(WmNews::getStatus,dto.getStatus());
        }
        query.orderByDesc(WmNews::getCreatedTime);
        //查询
        IPage<WmNews> iPage = page(page, query);
        //返回分页对象
        return new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());

    }
    @Autowired
    private IWmNewsMaterialService newsMaterialService;

    /**
     * @Lazy解决循环依赖问题
     */
    @Autowired
    @Lazy
    private IAuditService auditService;

    @Override
    public ResponseResult submit(WmNewsInfoDto dto) {
        //自媒体文章发布、修改、保存草稿
        //获取线程中的user
        User user = MediaThreadLocalUtil.get();
        if (user==null) {
            //如果用户不存在，返回提示：需要登录
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判定文章id是否存在，存在则修改
        if (dto.getId()!=null) {
            //先删除所有和当前文章id相关联的文章-素材表里的数据
            LambdaQueryWrapper<WmNewsMaterial> query=new LambdaQueryWrapper<>();
            query.eq(WmNewsMaterial::getNewsId,dto.getId());
            newsMaterialService.remove(query);
        }
        WmNews wmNews=createWmNews(dto,user.getId());
        List<ImageDto> images=new ArrayList<>();
        List<ImageDto> imageDtoList=getImageListFromContent(dto.getContent());
        //判断文章封面类型是否为自动
        if (dto.getType()==-1) {
            //为自动
            if (imageDtoList.size()>0&&imageDtoList.size()<3) {
                images = imageDtoList.subList(0, 1);
                wmNews.setImages(JSON.toJSONString(images));
                wmNews.setType(1);
            }else if (imageDtoList.size()>=3){
                images = imageDtoList.subList(0, 3);
                wmNews.setImages(JSON.toJSONString(images));
                wmNews.setType(3);
            }else {
                wmNews.setType(0);
            }
        }else {
            images = dto.getImages();
        }
        //修改或保存文章
        saveOrUpdate(wmNews);
        //判断是否是保存草稿
        if (dto.getStatus()==1) {
            //不是草稿，重新添加文章-素材表的数据
            //保存内容图
            saveImage(imageDtoList,wmNews.getId(),0);
            //保存主图
            saveImage(images,wmNews.getId(),1);
            //异步审核
            auditService.audit(wmNews);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //根据id查询文章
        WmNews wmNews = getById(dto.getId());
        //判断文章是否存在
        if (wmNews==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断文章是否发布
        if (wmNews.getStatus()!=9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //修改文章状态
        wmNews.setEnable(dto.getEnable()==1?true:false);
        updateById(wmNews);
        //发送消息，修改文章状态
        kafkaTemplate.send(downorup,wmNews.getArticleId().toString(),dto.getEnable()==1?"true":"false");
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findPageByName(NewsAuthDto dto) {
        //查看文章列表
        //构建查询条件
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> query=new LambdaQueryWrapper<>();
        query.orderByDesc(WmNews::getCreatedTime);
        query.like(!StringUtils.isEmpty(dto.getTitle()), WmNews::getTitle, dto.getTitle());
        //分页查询
        IPage<WmNews> iPage = page(page, query);
        //封装vo
        List<WmNews> records = iPage.getRecords();
        List<WmNewsVo> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(records)) {
            for (WmNews wmNews : records) {
                //查询用户信息
                WmUser wmUser = userService.getById(wmNews.getUserId());
                //创建vo并封装
                WmNewsVo vo = new WmNewsVo();
                BeanUtils.copyProperties(wmNews, vo);
                vo.setAuthorName(wmUser.getName());
                list.add(vo);
            }
        }
        //返回
        return new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), list);
    }

    @Autowired
    private IWmUserService userService;
    @Override
    public ResponseResult findNewsVoById(Integer id) {
        //查看文章详情
        WmNews wmNews = getById(id);
        //查询用户信息
        WmUser wmUser = userService.getById(wmNews.getUserId());
        //创建vo并封装
        WmNewsVo vo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, vo);
        vo.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult authFail(WmNewsAuthDto dto) {
        //人工审核驳回文章
        //根据id查询文章
        WmNews wmNews = getById(dto.getId());
        //设置驳回原因
        if (!StringUtils.isEmpty(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        //设置状态并修改
        wmNews.setStatus(dto.getStatus());
        updateById(wmNews);
        //返回
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult authPass(WmNewsAuthDto dto) {
        //人工审核通过文章
        //根据id查询文章
        WmNews wmNews = getById(dto.getId());
        //设置状态
        wmNews.setStatus(dto.getStatus());
        //调用审核
        auditService.audit(wmNews);
        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Value("${topic.downorup}")
    private String downorup;
    /**
     * 获取内容中的图片集合
     * @param content
     * @return
     */
    private List<ImageDto> getImageListFromContent(String content) {
        List<ImageDto> list=new ArrayList<>();
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if ("image".equals(contentDto.getType())) {
                ImageDto imageDto=new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                list.add(imageDto);
            }
        }
        return list;
    }

    /**
     * 保存图片到素材-文章表
     * @param images
     * @param id
     * @param type
     */
    private void saveImage(List<ImageDto> images, Integer id, int type) {
        int order=0;
        for (ImageDto image : images) {
            WmNewsMaterial wmNewsMaterial=new WmNewsMaterial();
            wmNewsMaterial.setNewsId(id);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd(order);
            wmNewsMaterial.setMaterialId(image.getId());
            order++;
            newsMaterialService.save(wmNewsMaterial);
        }
    }

    /**
     * 创建自媒体文章
     * @param dto
     * @param id
     * @return
     */
    private WmNews createWmNews(WmNewsInfoDto dto, Integer id) {
        WmNews wmNews=new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        wmNews.setUserId(id);
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setImages(JSON.toJSONString(dto.getImages()));
        return wmNews;
    }
}
